package com.express.sys.controller;

import com.alibaba.fastjson.JSONObject;
import com.express.entity.Token;
import com.express.entity.User;
import com.express.entity.UserRole;
import com.express.mybatis.PageResult;
import com.express.mybatis.Result;
import com.express.service.TokenService;
import com.express.sys.service.UserService;
import com.express.util.MD5Util;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 用户控制器
 *
 * @author zhouling
 * @since 2018年5月28日 下午3:54:00
 **/
@RestController
@RequestMapping({"/user"})
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    UserService userService;

    @Autowired
    TokenService tokenService;

    @PostMapping({"/get"})
    public Result get(@RequestParam("id") Integer id) {
        User user = this.userService.getById(id);
        Result result = new Result();
        result.setData(user);
        return result;
    }

    @CrossOrigin
    @PostMapping({"/list"})
    public PageResult list(@RequestBody PageResult page) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<User> list = this.userService.getList();
        PageResult result = new PageResult(list);
        return result;
    }

    @Transactional
    @PostMapping({"/add"})
    public Result add(@RequestBody User user) throws Exception {
        Result result = new Result();
        if ((user.getUsername() == null) || ("".equals(user.getUsername().trim()))) {
            result.error("用户名不能为空", "501");
            return result;
        }
        if ((user.getPassword() == null) || ("".equals(user.getPassword().trim()))) {
            result.error("密码不能为空", "501");
            return result;
        }
        if ((user.getPhone() == null) || ("".equals(user.getPhone().trim()))) {
            result.error("手机号不能为空", "501");
            return result;
        }
        List<User> list = this.userService.getByUsername(user.getUsername());
        if ((list != null) && (list.size() > 0)) {
            result.error("用户已存在", "500");
            return result;
        }
        try {
            user.setPassword(MD5Util.md5(user.getPassword()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        user.setNickname(user.getUsername());
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        this.userService.add(user);

        String[] roleIdList = user.getRoleId().split(",");
        for (int i = 0; i < roleIdList.length; i++) {
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(Integer.valueOf(Integer.parseInt(roleIdList[i])));
            this.userService.addURole(userRole);
        }
        result.setData(user);
        return result;
    }

    @Transactional
    @PostMapping({"/update"})
    public Result update(@RequestBody User user)
            throws Exception {
        if ((user.getPassword() != null) && (!"".equals(user.getPassword()))) {
            user.setPassword(MD5Util.md5(user.getPassword()));
            this.userService.updatePassword(user);
        }
        this.userService.deleteURole(user.getId());

        String[] roleIdList = user.getRoleId().split(",");
        for (int i = 0; i < roleIdList.length; i++) {
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(Integer.valueOf(Integer.parseInt(roleIdList[i])));
            this.userService.addURole(userRole);
        }
        Result result = new Result();
        return result;
    }

    @PostMapping({"/delete"})
    public Result delete(@RequestBody JSONObject json) {
        Result result = new Result();
        String[] idsArr = json.getString("ids").split(",");
        int[] idsInt = new int[idsArr.length];
        for (int i = 0; i < idsArr.length; i++) {
            idsInt[i] = Integer.parseInt(idsArr[i]);
        }
        this.userService.delete(idsInt);
        return result;
    }

    @PostMapping({"/login"})
    public Result login(@RequestBody User user)
            throws Exception {
        try {
            Result result = new Result();
            if ((user.getUsername() == null) || ("".equals(user.getUsername().trim()))) {
                result.error("用户名不能为空", "501");
                return result;
            }
            if ((user.getPassword() == null) || ("".equals(user.getPassword().trim()))) {
                result.error("密码不能为空", "501");
                return result;
            }
            user.setPassword(MD5Util.md5(user.getPassword()));

            List<User> list = this.userService.login(user);
            if ((list == null) || (list.size() == 0)) {
                result.error("用户或密码错误", "500");
                return result;
            }
            if (StringUtils.isNotBlank(user.getSource()) && user.getSource().equals("website")) {
                if (!user.getUsername().equals("楚莹")) {
                    result.error("官网登录出错请联系开发人员", "502");
                    return result;
                }
            }
            if (list.size() > 1) {
                result.error("登录出错请联系开发人员", "502");
                return result;
            }
            List<UserRole> roleList = this.userService.listUserRole(((User) list.get(0)).getId());
            String roleId = "";
            for (int i = 0; i < roleList.size(); i++) {
                roleId = roleId + ((UserRole) roleList.get(i)).getRoleId() + ",";
            }
            if (roleId.length() > 0) {
                roleId = roleId.substring(0, roleId.length() - 1);
            }
            Date now = new Date();
            Token token = new Token();
            token.setToken(UUID.randomUUID().toString());
            token.setUserId(((User) list.get(0)).getId());
            token.setUserName(((User) list.get(0)).getUsername());
            token.setRoleId(roleId);
            token.setCreateTime(now);
            token.setUpdateTime(now);
            token.setExpireTime(new Date(now.getTime() + 7200000L));
            this.tokenService.add(token);
            result.setData(token);
            result.setMessage("登录成功");
            // 删除过期的token
            this.tokenService.clearExpireToken();
            return result;
        } catch (Exception e) {
            log.error("登录出错请联系开发人员", e);
            throw new RuntimeException(e);
        }
    }

    @PostMapping({"/logout"})
    public Result logout(HttpServletRequest request)
            throws Exception {
        String token = request.getHeader("token");
        this.tokenService.remove(token);
        Result result = new Result();
        return result;
    }

    @Transactional
    @GetMapping({"/test"})
    public Result test() {
        Result result = new Result();
        User user = new User();
        user.setUsername("aaa");
        this.userService.add(user);

        User user2 = new User();
        user2.setUsername("bbb");
        this.userService.add(user2);
        int i = 1 / 0;
        return result;
    }

    public boolean verify(String token) {
        return this.tokenService.verify(token);
    }
}
